from flask import Blueprint,jsonify,request
from db import db1
import json
from utils.comm import get_data
users_bp = Blueprint('users',__name__)


def xtree(data):
    list = []
    tree = {}
    if not data:
        return data
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if pid == 0:
            list.append(j)
        else:
        # 查看父类下有没有子类
            if 'son' not in tree[pid]:
                # 如果没有初始化列表
                tree[pid]['son'] = []
            # 把子类加到父类列表中
            tree[pid]['son'].append(j)
    return list


import time
@users_bp.route('/cateM', methods=['POST', 'GET'])
def cateM():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into cates values(0,'%s',%d,%s)""" % (data['name'], int(data['pid']), data['params'])
        db1.update(sql)
        return jsonify({'code': 200})

    elif request.method == 'GET':
        time.sleep(0.001)
        sql = """select * from  cates"""
        res = db1.fid_all(sql)
        data = xtree(res)
        return jsonify({'code': 200, "list": data})

@users_bp.route('/classt',methods=['POST', 'GET'])
def classt():
    if request.method == 'GET':
        sql =  """select * from  teacher"""
        res = db1.fid_all(sql)
        return jsonify({'code': 200,'list':res})

#通过分类id获取分类参数
@users_bp.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'params':res['params']})


@users_bp.route('/courseM', methods=['POST', 'GET'])
def courseM():
    data = get_data()
    if data['params']:
        sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
        data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
        int(data['status']))
    else:
        sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
        data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']), int(data['status']))

    db1.update(sql)
    return jsonify({"code": 200})


